package com.rice.zuul.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ZookeeperLock {

    /**
     * https://blog.csdn.net/sinat_19687693/article/details/50977567
     * https://blog.csdn.net/qiangcuo6087/article/details/79067136 原理分析
     * http://www.jasongj.com/zookeeper/fastleaderelection/  ZK的选举过程分析
     *
     * Curator参数说明
     * 1.connectString zookeeper服务器的连接
     * 2.retryPolicy 重试策略，默认有四个ExponentialBackoffRetry、RetryNtime、Retryonetime、RetryUtilElapsed
     * 3.sessionTimeoutMs 回话超时时间，默认60 000ms
     * 4.connectionTimeoutMs 连接创建超时时间， 默认15 000ms
     *
     * RetryPolicy
     * 1.retryCount 已经重试的次数，如果是第一次，那么改值为0
     * 2.elapsedTimeMs 从第一次尝试开始已经花费的时间
     * 3.Sleepeer 用于sleep指定时间。不建议使用Thread.sleep()操作
     *
     * ExponentialBackoffRetry
     * 1.baseSleepTimeMs 初始sleep时间
     * 2.maxRetries 最大重试次数
     * 3.maxSleepMs 最大sleep时间
     * @throws Exception
     */
    public void tryLock() throws Exception{
        //创建zookeeper的客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("10.21.41.181:2181,10.21.42.47:2181,10.21.49.252:2181", retryPolicy);
        client.start();
        //创建分布式锁, 锁空间的根节点路径为/curator/lock
        InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
        mutex.acquire();
        //获得了锁, 进行业务流程
        System.out.println("Enter mutex");
        //完成业务流程, 释放锁
        mutex.release();
        //关闭客户端
        client.close();
    }
}
